package com.mobilebsc.httpclient.callback;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.mobilebsc.datatype.StrategicGoal;

public class StrategicGoalHttpResponseHandler extends JsonHttpResponseHandler {

	private static final String TAG = "StrategicGoalHttpResponseHandler";
	private IAsyncTaskCompleteListener<List<StrategicGoal>> callback;
	protected List<StrategicGoal> strategicGoalsList;

	public StrategicGoalHttpResponseHandler(
			IAsyncTaskCompleteListener<List<StrategicGoal>> callback) {
		super();
		this.callback = callback;
		strategicGoalsList = null;
	}

	@Override
	public void onStart() {
		Log.i(TAG, "onStart = loading data");
	}

	@Override
	public void onSuccess(JSONArray strategicGoals) {

		Log.i(TAG, "onSuccess0 = JSON length " + strategicGoals.length()
				+ ", JSON string " + strategicGoals.toString());

		strategicGoalsList = new ArrayList<StrategicGoal>();
		JSONObject strategicGoalJSON = new JSONObject();

		if (strategicGoals.length() == 0) {
			strategicGoalsList.add(new StrategicGoal());
		} else {
			for (int i = 0; i < strategicGoals.length(); i++) {
				try {
					strategicGoalJSON = strategicGoals.getJSONObject(i);
					StrategicGoal strategicGoal = new StrategicGoal(
							strategicGoalJSON);
					strategicGoalsList.add(strategicGoal);
				} catch (JSONException e) {
					Log.e(TAG, "onSuccess = " + e.toString());
				}
			}
		}
	}

	@Override
	public void onSuccess(JSONObject singleStrategicGoal) {
		strategicGoalsList = new ArrayList<StrategicGoal>();

		if (singleStrategicGoal == null) {
			strategicGoalsList.add(new StrategicGoal());
		} else {
			try {
				StrategicGoal strategicGoal = new StrategicGoal(
						singleStrategicGoal);
				strategicGoalsList.add(strategicGoal);
			} catch (JSONException e) {
				Log.e(TAG, "onSuccess = " + e.toString());
			}
		}
	}

	@Override
	public void onFinish() {
		Log.i(TAG, "onFinish = finished");
		callback.onTaskComplete(strategicGoalsList);
	}

	@Override
	public void onFailure(Throwable e, String response) {
		Log.e(TAG, "onFailure = " + e.toString() + "\n\n" + response);
	}
}